package com.hdcircles.autoform.ui.label.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.cengalabs.flatui.views.FlatCheckBox;
import com.cengalabs.flatui.views.FlatRadioButton;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.hdcircles.autoform.R;
import com.hdcircles.autoform.app.App;
import com.hdcircles.autoform.app.Constants;
import com.hdcircles.autoform.base.BaseActivity;
import com.hdcircles.autoform.model.bean.ChooseQuestionBean;
import com.hdcircles.autoform.model.bean.FormBean;
import com.hdcircles.autoform.model.bean.QuestionBean;
import com.hdcircles.autoform.presenter.AddSurveyPresenter;
import com.hdcircles.autoform.presenter.contract.AddSurveyContract;
import com.hdcircles.autoform.util.ProgressDialogUtil;
import com.hdcircles.autoform.util.SharedPreferenceUtil;
import com.hdcircles.autoform.util.SnackbarUtil;
import com.hdcircles.autoform.util.SystemUtil;
import com.hdcircles.autoform.util.ToastUtil;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by simon on 16/9/27.
 */

public class AddSurveyActivity extends BaseActivity<AddSurveyPresenter> implements AddSurveyContract.View, View.OnClickListener {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_question_amount)
    TextView tvQuestionAmount;
    @BindView(R.id.bt_add)
    Button btAdd;
    @BindView(R.id.ll_qt_amount)
    LinearLayout llQtAmount;
    @BindView(R.id.fab_text)
    FloatingActionButton fabText;
    @BindView(R.id.fab_multi)
    FloatingActionButton fabMulti;
    @BindView(R.id.fab_time)
    FloatingActionButton fabTime;
    @BindView(R.id.fab_location)
    FloatingActionButton fabLocation;
    @BindView(R.id.float_menu)
    FloatingActionsMenu floatMenu;
    @BindView(R.id.tv_question_title)
    TextView tvQuestionTitle;
    @BindView(R.id.tv_survey_title)
    TextView tvSurveyTitle;
    @BindView(R.id.ll_question_info)
    LinearLayout llQuestionInfo;
    @BindView(R.id.bt_first)
    Button btFirst;
    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;

    private int currentIndex = 0;

    private List<QuestionBean> questionList;


    @Inject
    FormBean formBean;

    private QuestionBean currentQuestionBean;

    @Inject
    QuestionBean initQuestion;

    private List<Button> btNumberList;

    private TreeMap<String, QuestionBean> questions;

    private Button currentButton;
    private ProgressDialog dialog;


    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_add_survey;
    }

    @Override
    protected void initEventAndData() {
        setToolBar(toolbar, "编辑问卷");
        questions = new TreeMap<>();
        questions.put(btFirst.getText().toString(), initQuestion);
        btNumberList = new ArrayList<>();
        btNumberList.add(btFirst);
        questionList = new ArrayList<>();
//        questionList.add(initQuestion);
        currentQuestionBean = initQuestion;
        currentButton = btFirst;
//        formBean.setQuestion(questionList);
        initQuestion.setQuestionId(btFirst.getText().toString());
        tvQuestionAmount.setText(getResources().getString(R.string.qt_number, "1"));
        editSurveyTitle();
    }


    @Override
    public void showError(String msg) {
        ProgressDialogUtil.close();
        SnackbarUtil.showShort(toolbar,msg);
    }

    @OnClick(R.id.bt_add)
    void addQuestion() {
        addQuestionButton();
    }

    private void addQuestionButton() {
        currentIndex += 1;
        Button button = new Button(this);
        btNumberList.add(button);
        QuestionBean questionBean = new QuestionBean();
        button.setTextSize(20);
        button.setBackgroundColor(getResources().getColor(R.color.custom_theme_primary));
        button.setText(String.valueOf(currentIndex + 1));
        questions.put(button.getText().toString(), questionBean);
        questionBean.setQuestionId(button.getText().toString());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(SystemUtil.dp2px(this, 42), SystemUtil.dp2px(this, 52));
        int margin = SystemUtil.dp2px(this, 12);
        params.setMarginStart(margin);
        llQtAmount.addView(button, currentIndex, params);
        button.setOnClickListener(this);
    }

    private int margin = SystemUtil.dp2px(App.getInstance(), 16);

    @OnClick(R.id.tv_survey_title)
    void setSurveyTitle() {
        editSurveyTitle();
    }

    private void editSurveyTitle() {
        final EditText editText = new EditText(this);
        editText.setSingleLine();
        if (null != formBean.getFormName()) editText.setText(formBean.getFormName());
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(R.string.edit_survey_title)
                .setView(editText, margin, margin, margin, 0)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String title = editText.getText().toString().trim();
                        formBean.setFormName(title);
                        tvSurveyTitle.setText(title);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        tvSurveyTitle.setText(formBean.getFormName());
                    }
                })
                .setCancelable(false);
        builder.show();
    }


    public void showProgress(){
        dialog = new ProgressDialog(this, R.style.AppTheme_Dark_Dialog);
        dialog.setMessage("正在保存");
        dialog.setIndeterminate(true);
        dialog.show();
    }

    public void closeProgress(){

        if (null!=dialog&&dialog.isShowing()){
            dialog.dismiss();
        }
    }

    @OnClick(R.id.tv_question_title)
    void setQuestionTitle() {
        showQuestionDialog(getResources().getString(R.string.edit_question_title), currentQuestionBean.getType());
    }


    @OnClick(R.id.fab_text)
    void addTextQuestion() {
        floatMenu.collapse();
        showQuestionDialog(getResources().getString(R.string.addText), Constants.TYPE_TEXT);
    }

    @OnClick(R.id.fab_multi)
    void addMultipleChooseQuestion() {
        floatMenu.collapse();
        Intent intent = new Intent(this, MultipleChoiceActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("question", currentQuestionBean);
        intent.putExtras(bundle);
        startActivityForResult(intent, Constants.TYPE_MULTIPLE_CHOOSE);
    }

    @OnClick(R.id.fab_time)
    void addTime() {
        floatMenu.collapse();
        showQuestionDialog(getResources().getString(R.string.add_time), Constants.TYPE_TIME);
    }

    @OnClick(R.id.fab_location)
    void addLocation() {
        floatMenu.collapse();
        showQuestionDialog(getResources().getString(R.string.add_location), Constants.TYPE_LOCATION);
    }

    @OnClick(R.id.fab_picture)
    void addPicture(){
        floatMenu.collapse();
        showQuestionDialog(getResources().getString(R.string.add_picture),Constants.TYPE_PICTURE);
    }

    @OnClick(R.id.fab_mould)
    void addMould(){
        floatMenu.collapse();
        Intent intent=new Intent(this,FormMouldActivity.class);
        startActivityForResult(intent,Constants.TYPE_MOULD);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.survey_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) onBackPressedSupport();
        if (item.getItemId() == R.id.survey_ok) {
            formBean.setCreator(SharedPreferenceUtil.getUserEmail());
            formBean.setQuestion(questionList);
            formBean.setTime(System.currentTimeMillis());
            formBean.setStatus(Constants.STATUS_INITIALIZATION);
            formBean.setFormId(SystemUtil.genID(System.currentTimeMillis()));
            Map<String,QuestionBean> resultMap=SystemUtil.sortMapByKey(questions);
            for (Map.Entry<String, QuestionBean> entry : resultMap.entrySet()) {
                if (entry.getValue().getType() != Integer.MAX_VALUE) {
                    QuestionBean questionBean = entry.getValue();
                    questionBean.setQuestionId(formBean.getFormId() + entry.getKey());
                    questionList.add(questionBean);
                }
            }
//            mPresenter.saveFormData(formBean);
            //TODO 创建地图
            mPresenter.createMap(formBean.getFormName());
//            finish();
            showProgress();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void saveFormSuccess(String msg) {
        closeProgress();
        ToastUtil.shortShow(msg);
        finish();
    }

    /**
     * 下方button 的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        currentButton = (Button) view;
        setButtonStatus(currentButton);
    }

    @OnClick(R.id.bt_first)
    void btFirstClick() {
        currentButton = btFirst;
        setButtonStatus(btFirst);
    }

    private void setButtonStatus(Button button) {
        button.setTextColor(Color.WHITE);
        button.setBackgroundColor(getResources().getColor(R.color.custom_theme_darker));
        mPresenter.getQuestion(questions, btNumberList, button);
    }

    @Override
    public void changeButtonStatus(Button button) {
        button.setTextColor(Color.BLACK);
        button.setBackgroundColor(getResources().getColor(R.color.custom_theme_primary));
    }

    @Override
    public void setCurrentQuestion(QuestionBean question) {
        String number = String.valueOf(btNumberList.indexOf(currentButton) + 1);
        tvQuestionAmount.setText(getResources().getString(R.string.qt_number, number));
        currentQuestionBean = question;
        setQuestionView(question);

    }

    @Override
    public void createMapSuccess(String tableId) {
        formBean.setTableId(tableId);
        mPresenter.saveFormData(formBean);
    }

    private void setQuestionView(QuestionBean question) {
        if (null == currentQuestionBean.getQuestionTitle()) {
            tvQuestionTitle.setText(R.string.question_title);
        } else {
            tvQuestionTitle.setText(currentQuestionBean.getQuestionTitle());
        }
        int margin = SystemUtil.dp2px(this, 8);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                , LinearLayout.LayoutParams.MATCH_PARENT);
        params.setMargins(margin, margin, margin, margin);
        params.gravity=Gravity.CENTER;
        llQuestionInfo.removeAllViews();
        TextView tv = new TextView(this);
        switch (question.getType()) {
            case Integer.MAX_VALUE:
                tvEmpty.setVisibility(View.VISIBLE);
                break;
            case Constants.TYPE_TEXT:
                tvEmpty.setVisibility(View.GONE);
                tv.setEnabled(false);
                tv.setHint("输入文本");
                tv.setGravity(Gravity.CENTER);
                tv.setTextSize(22);
                llQuestionInfo.addView(tv, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                break;
            case Constants.TYPE_LOCATION:
                tvEmpty.setVisibility(View.GONE);
                ImageView ivLocation = new ImageView(this);
                ivLocation.setImageDrawable(getDrawable(R.drawable.ic_location));
                llQuestionInfo.addView(ivLocation,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                        , LinearLayout.LayoutParams.MATCH_PARENT));
                break;
            case Constants.TYPE_PICTURE:
                tvEmpty.setVisibility(View.GONE);
                ImageView ivPicture = new ImageView(this);
                ivPicture.setImageDrawable(getDrawable(R.drawable.ic_picture));
                llQuestionInfo.addView(ivPicture,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                        , LinearLayout.LayoutParams.MATCH_PARENT));
                break;
            case Constants.TYPE_TIME:
                tvEmpty.setVisibility(View.GONE);
                ImageView imageView = new ImageView(this);
//                imageView.setBackgroundResource(R.drawable.ic_time_large);
                imageView.setImageDrawable(getDrawable(R.drawable.ic_time_large));
                llQuestionInfo.addView(imageView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
                        , LinearLayout.LayoutParams.MATCH_PARENT));
                break;
            case Constants.TYPE_SINGLE_CHOOSE:
                tvEmpty.setVisibility(View.GONE);
                RadioGroup radioGroup = new RadioGroup(this);
                for (ChooseQuestionBean choiceBean : currentQuestionBean.getChooseQuestion()) {
                    FlatRadioButton button = (FlatRadioButton) View.inflate(this, R.layout.view_radio, null);
                    button.setTextSize(18);
                    button.setText(choiceBean.getInfo());
                    radioGroup.addView(button);
                }
                llQuestionInfo.addView(radioGroup, params);
                break;
            case Constants.TYPE_MULTIPLE_CHOOSE:
                tvEmpty.setVisibility(View.GONE);
                LinearLayout linearLayout = new LinearLayout(this);
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                for (ChooseQuestionBean choice : currentQuestionBean.getChooseQuestion()) {
                    FlatCheckBox checkBox = (FlatCheckBox) View.inflate(this, R.layout.view_check_box, null);
                    checkBox.setTextSize(18);
                    checkBox.setText(choice.getInfo());
                    linearLayout.addView(checkBox);
                }
                llQuestionInfo.addView(linearLayout, params);
                break;
        }
    }

    private void showQuestionDialog(String title, final int type) {
        View llContainer= View.inflate(this,R.layout.dialog_question_title,null);
        final EditText etTitle= (EditText) llContainer.findViewById(R.id.et_question_title);
        final FlatCheckBox cbRequired= (FlatCheckBox) llContainer.findViewById(R.id.cb_required);
        if (null != currentQuestionBean.getQuestionTitle()) etTitle.setText(currentQuestionBean.getQuestionTitle());
        cbRequired.setChecked(currentQuestionBean.isRequired());
        if (type==Integer.MAX_VALUE) cbRequired.setVisibility(View.GONE);
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(title)
                .setView(llContainer)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String question = etTitle.getText().toString().trim();
                        currentQuestionBean.setQuestionTitle(question);
                        currentQuestionBean.setType(type);
                        currentQuestionBean.setRequired(cbRequired.isChecked());
                        tvQuestionTitle.setText(question);
                        setQuestionView(currentQuestionBean);
                    }
                })
                .setNegativeButton(R.string.cancel, null);
        builder.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.TYPE_MULTIPLE_CHOOSE:
                if (null != data) {
                    currentQuestionBean = data.getParcelableExtra("question");
                    questions.put(currentButton.getText().toString(), currentQuestionBean);
                    setQuestionView(currentQuestionBean);
                }
                break;
            case Constants.TYPE_MOULD:
                if (null!=data){
                    FormBean form=data.getParcelableExtra("form");
                    tvSurveyTitle.setText(form.getFormName());
                    formBean.setFormName(form.getFormName());
                    List<QuestionBean> questionList=form.getQuestion();
                    for (int i=0;i<questionList.size();i++){
                        QuestionBean question=questionList.get(i);
                        addQuestionButton();
                        String index=String.valueOf(i+1);
                        questions.put(index, question);
                        if (i==0){
                            currentQuestionBean=question;
                            setQuestionView(currentQuestionBean);
                        }
                    }
                }
                break;
        }
    }
}
